/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.by.wms.controller;

import cn.by.wms.service.DownloadService;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.smart.core.annotation.NoWapperX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;


//Restful Api
@RestController
@Slf4j
@RequestMapping("/api/download")
public class DownloadController {
    @Autowired
    private DownloadService downloadService;


    @GetMapping
    @NoWapperX
    public void downloadFile(HttpServletResponse response, @RequestParam("fileName") String fileName) {
        // 构建完整的文件下载 URL
        String fileUrl = "http://img.clz.com/images/" + fileName;

        try(   // 发起 HTTP GET 请求获取文件输入流
               InputStream inputStream = HttpUtil.createGet(fileUrl).execute().bodyStream();)
        {


            if (inputStream == null) {
                // 如果文件不存在，返回 404 错误
                response.setStatus(HttpStatus.NOT_FOUND.value());
                response.getWriter().write("File not found: " + fileName);
                return;
            }

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");

            // 使用 IoUtil 将输入流写入响应输出流
            IoUtil.copy(inputStream, response.getOutputStream());

            // 确保输出流被刷新
            response.flushBuffer();
        } catch (IOException e) {
            // 处理异常情况
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            try {
                response.getWriter().write("Error downloading file: " + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }


}
